package com.ssyt.jfinal.core.article;

import com.jfinal.aop.Duang;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.RenderFactory;
import com.jfinal.upload.UploadFile;
import com.ssyt.jfinal.core.common.BaseController;
import com.ssyt.jfinal.core.common.model.Article;
import com.ssyt.jfinal.core.common.utils.PageConstants;
import com.ssyt.jfinal.core.common.utils.PageModel;

/**
 * 所有 sql 与业务逻辑写在 Model 或 Service 中，不要写在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 *
 * @author Liberty
 * @since Jan 9, 2017
 */
public class ArticleController extends BaseController {

    /**
     * JFinal 中的 AOP 被划分为控制层 AOP 以及业务层 AOP，如果要在业务层使用AOP，需要通过Duang.duang()或Enhancer.enhance()进行增强！
     */
    private ArticleService articleService = Duang.duang(ArticleService.class);

//    @Before(ArticleInterceptor.class)
//    public void list() {
//        // 创建单例的ArticleService对象
//        // ArticleService articleService1 = Duang.duang("key", ArticleService.class);
//        // ArticleService articleService2 = Duang.duang("key", ArticleService.class);
//        // System.out.println(articleService1 == articleService2);
//        setAttr("article", "一篇文章.");
//        render("list.jsp");
//    }

    public void add() {
    	Article article = getModel(Article.class);
    	article.save();
    	//articleService.add(article);
    	render(RenderFactory.me().getRedirectRender("/article/list.html"));
    }
    
    public void delete() {
        articleService.delete(getParaToInt());
        renderJson("result", "success");
    }

    public void list() {
    	Integer pageNo = getParaToInt();
    	if(pageNo == null) {
    		pageNo = PageConstants.PAGE_NUMBER;
    	}
    	String title = getPara("title");
//    	List<Record> articleList = Db.find("SELECT a.title, a.content, a.create_time AS createTime, a.read_times AS readTimes, u.code FROM article a, user u WHERE a.user_id = u.id");
    	Page<Record> articlePage = articleService.list(pageNo, title);
    	PageModel<Record> articlePageModel = new PageModel<>(articlePage.getList(), articlePage.getPageNumber(), articlePage.getPageSize(), articlePage.getTotalPage(), articlePage.getTotalRow());
    	setAttr("articlePageModel", articlePageModel);
    	setAttr("title", title);
    	render("article-crud.jsp");
    }
    
    public void update() {
    	Article article = getModel(Article.class);

    	article.update();
    	//articleService.update(article);
    	//String code = getPara("authorCode");
    	render(RenderFactory.me().getRedirectRender("/article/list.html"));
    }
    
    
    /**
     * 文件操作
     */
    public void upload() {
        UploadFile file = getFile();
        System.out.println(file.getUploadPath());
        System.out.println(file.getOriginalFileName());
    }
 
    public void download(){
    	renderFile("bb.png");
    }
    
}
